from django.core.paginator import Paginator
import warnings
try:
	from django.contrib.gis.geos import fromstr
except ImportError:
	## pass well known text through if we cannot
	## make a real geometry object
	fromstr = lambda x: x
	
__all__ = ["ResultList"]

def queryBox(q):
	w, s, e, n = q.split(",")
	wkt = "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" % (
		w, s,
		w, n,
		e, n,
		e, s,
		w, s
		)
	return fromstr(wkt)
def queryPolygon(q):
	coords = q.split(",")
	def _f():
		for i in range(len(coords)/2):
			yield "%s %s" % (coords[2*i+1], coords[2*i])
	wkt = "POLYGON((" + ",".join(list(_f())) + "))"
	return fromstr(wkt)

class ResultList(object):
	def __init__(self, request, model):
		self.query = request.GET.copy()
        #print self.query
		self.model = model
		self.opts = model._meta.search
		self.manager = model._default_manager

		self.page = 1
		self.count = 10
		self.sort = []
		self.get_lookup_opts(self.query)

	def get_lookup_opts(self, query):
		"""
		Sets the lookup option attributes on self (i.e. current page,
		results per page, etc.) from the given query dictionary.
		Removes these options from the query dictionary as well.
		"""
		for k in ["page", "count"]:
			if k in query:
				setattr(self, k, int(query[k]))
				del query[k]
		for k in ["sort"]:
			if k in query:
				setattr(self, k, query[k])
				del query[k]

	def results(self):
		filter = {}
		statements = []
		search_terms = dict(map(lambda x: (x["name"], x),
					self.opts.search_terms))

		for k in self.query:
			if not self.query[k]:
				continue
			if k in search_terms:
                #warnings.warn(k)
				spec = search_terms[k]
				if spec["type"] == "django":
					filter[spec["filter"]] = self.query[k]
				elif spec["type"] == "rdf":
					s = "\t?resource <%s> '%s'" % (
						spec["uri"],
						self.query[k].replace("'", "")
						)
					statements.append(s)
				elif spec["type"] == "geodjango":
					if spec["query"] == "geo:box":
						filter[spec["filter"]] = queryBox(self.query[k])
					elif spec["query"] == "geo:polygon":
						filter[spec["filter"]] = queryPolygon(self.query[k])
					
        #print statements
		if statements:
			sparql = "SELECT DISTINCT ?resource {\n"
			sparql = sparql + " .\n".join(statements)
			sparql = sparql + "\n}"
			#print sparql
			qs = self.manager.sparql_filter(sparql)
		else:
            #print filter
			qs = self.manager.filter()

		qs = qs.filter(**filter)
		paginator = Paginator(qs, self.count, allow_empty_first_page=True)
		page = paginator.page(self.page)
		page.model = self.model
		return page
